package com.gukewen.alibabacloudoss.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/*
 * @author: xiaogu
 * @date: 2022/11/9
 * @description: 阿里云OSS工具类
 */
@Component
public class AliOSSUtils {

    // Endpoint以杭州为例，其它Region请按实际情况填写。
    private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
// 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider;
    {
        try {
            credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

    // 您的Bucket名称。
    private String bucketName = "xiaogu-web";


    /*
     * 实现上传图片到阿里云OSS
     */
    public String upload(MultipartFile file) throws Exception{
        //获取上传文件的输入流
        InputStream inputStream = file.getInputStream();

        //避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        System.out.println(fileName);

        //上传文件到OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint,  credentialsProvider);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = endpoint.split("://")[0] + "//" + bucketName + "." + endpoint.split("://")[1] + "/" + fileName;

        //关闭OSSClient。
        ossClient.shutdown();
        return url;
    }
}
